package com.zhu.fastFoodRestaurantOrderSystem.repository.impl;

import com.zhu.fastFoodRestaurantOrderSystem.exception.BusinessException;
import com.zhu.fastFoodRestaurantOrderSystem.exception.ErrorCode;
import com.zhu.fastFoodRestaurantOrderSystem.model.Order;
import com.zhu.fastFoodRestaurantOrderSystem.repository.OrderRepository;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class OrderRepositoryImpl implements OrderRepository {

    private static final Map<String, Order> orderMap = new ConcurrentHashMap<>();
    @Override
    public Order findById(String orderId) {
        Order order = orderMap.get(orderId);
        if (order == null){
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND);
        }
        return order;
    }

    @Override
    public void save(Order order) {
        Order put = orderMap.put(order.getOrderId(), order);
        if (put != null){
            throw new BusinessException(ErrorCode.ORDER_NOT_CREATABLE);
        }
    }

    @Override
    public void update(Order order) {
        Order put = orderMap.put(order.getOrderId(), order);
        if (put == null){
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND);
        }
    }

    @Override
    public void delete(String orderId) {
        Order remove = orderMap.remove(orderId);
        if (remove == null){
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND);
        }
    }
}
